<template>
	<div class=" ">
		<div class="contentTop userSelectNone">
			<div class="mobileContentTitle overflow">
				{{activeItem.otherName}}
				<span style="color: #ccc;">[{{activeItem.isGroup===1?"群":""}}Id号:{{activeItem.activeId}}]</span>
				<span class="font12 marginL10">在线人数:</span> <span class="font12 ">[{{onlineUsersLength}}]</span>
			</div>
		</div>
		<div class="mobileContentMiddle scrollbarOverflow userSelectNone" ref="MobilScrollBoxRef"
			@scroll="handleWatchScroll">
			<div class="contentBox" v-for="key,index in messageList" :key="key.messageId">
				<div class="contentBoxLeft" v-if="key.fromId!=activeItem.fromId">
					<div class="fromPhoto">
						<el-image class="imageCls borderr50" :src="key.fromUrl+'?w=50&h=50&q=75'" fit="fill"
							:preview-src-list="[key.fromUrl]">
							<div slot="error" class="image-slot">
								<el-image class="imageCls borderr50"
									:src="$handledImageError(key.fromUrl+'?w=50&h=50&q=75','tx')" fit="fill"
									:preview-src-list="[$handledImageError(key.fromUrl,'tx')]">
								</el-image>
							</div>
						</el-image>
					</div>
					<div class="contentName" v-if="isShowName">
						{{key.userName || key.fromName}}
					</div>
					<div class="contentMessageDateBox">
						<div class="contentMessageDate">
							{{ formatDate(key.createTime)}}
						</div>
					</div>
					<div class="fromMessage">
						<div v-if="key.type===1">
							<leng-message :message='key.message' :maslength="key.msglength"></leng-message>
						</div>
						<div v-else-if="key.type===11">
							<el-image lazy class="msgImagesCls " :src="key.imagesUrl+'?w=300&h=250&q=30'" fit="fill"
								@error.once="handledImagesErrorOne(key.imagesUrl,index)"
								:preview-src-list="messagePreviewList"
								:initialIndex="originalPreviewList.indexOf(key.imagesUrl)">
							</el-image>
						</div>
					</div>


				</div>
				<div class="contentBoxRight" v-else>
					<div class="fromPhoto">
						<el-image class="imageCls borderr50" :src="key.fromUrl+'?w=50&h=50&q=75'" fit="fill"
							:preview-src-list="[key.fromUrl]">
							<div slot="error" class="image-slot">
								<el-image class="imageCls borderr50"
									:src="$handledImageError(key.fromUrl+'?w=50&h=50&q=75','tx')" fit="fill"
									:preview-src-list="[$handledImageError(key.fromUrl,'tx')]">
								</el-image>
							</div>
						</el-image>
					</div>
					<div class=" contentNameRight" v-if="isShowName">
						{{key.userName || key.fromName}}
					</div>
					<div class="contentMessageDateBox">
						<div class="contentMessageDate">
							{{ formatDate(key.createTime)}}
						</div>
					</div>
					<div class="fromMessage">
						<div v-if="key.type===1">
							<leng-message :message='key.message' :maslength="key.msglength"></leng-message>
						</div>
						<div v-else-if="key.type===11">
							<el-image lazy class="msgImagesCls " :src="key.imagesUrl+'?w=300&h=250&q=30'" fit="fill"
								@error.once="handledImagesErrorOne(key.imagesUrl,index)"
								:preview-src-list="messagePreviewList"
								:initialIndex="originalPreviewList.indexOf(key.imagesUrl)">
							</el-image>
						</div>
					</div>
				</div>
			</div>

		</div>
		<div class="mobilemobileMsgTipBox" v-show="isShowNewmobileTip">
			<div class="mobileMsgTip" @click="handlerShowTip">
				<i class="iconfont icon-shuangxiangxiajiantou"></i><span></span>
			</div>
		</div>

		<div class="mobilemobileMsgTipBox" v-show="isShowNewmobileMsgTip">
			<div class="mobileMsgTip" @click="handlerShowTip">
				<i class="iconfont icon-shuangxiangxiajiantou"></i><span>有新消息</span>
			</div>
		</div>
		<div class="msgBottomBox">
			<div class="contentDown">
				<el-input type="textarea" :autosize="{ minRows: 4, maxRows:4}" resize='none'
					@keydown.enter.native="handleEnterKey" :maxlength='contentMaxlength' placeholder="善语结善缘,恶语伤人心"
					v-model="activeItem.message">
				</el-input>
			</div>
			<div class="hintContentButtom">
				<div class="buttomLeft">
					<div class="cursorPointer" @click="dialogVisibleMobileSendImage=true">
						<i class="iconfont icon-tupian"></i>
					</div>
					<div class="emojiButton" ref="RefEmojiElement">
						<i @click="VisibleEmojiElement=true" class="cursorPointer iconfont icon-biaoqingbao"></i>
						<emoji-Element style="width: 96vw;position:absolute;margin: 0 auto;left:-55px;top: -510px;"
							:Visible="VisibleEmojiElement"
							@handledVisibleEmojiElementChildEmit='handledVisibleEmojiElementChildEmit'></emoji-Element>
					</div>
				</div>
				<div class="buttomReft">
					<div class="hintContentLength">
						<i class="hintContentNowLength"
							v-show="activeItem.message.length!=0">{{activeItem.message.length}}</i>
						<i class="" v-show="activeItem.message.length>12000"> / {{contentMaxlength}}</i>
					</div>
					<el-button class="" size='mini' type="primary" :disabled="activeItem.message.length==0"
						@click="handleSend">发送</el-button>
				</div>
			</div>
		</div>
		<el-dialog center :title="`发送至:${activeItem.otherName}`" :visible.sync="dialogVisibleMobileSendImage"
			@close="handleCloseSendImage" width="80%" append-to-body>
			<div class="textCenter">
				<single-upload v-model="activeItem.imagesUrl"></single-upload>
				<el-button :disabled='activeItem.imagesUrl==""' style="margin-top: 20px;"
					@click="handleSendImage">发送</el-button>
			</div>
		</el-dialog>

	</div>
</template>

<script>
	import {
		IMSend,
		IMGetMessage
	} from "@/api/message"
	import {
		getdate,
		DateIfSimilar,
		formatDateHMS
	} from "@/utils/base"
	import Storage from "@/utils/session.js"
	import {
		debounce
	} from "@/utils/common.js";
	import singleUpload from "@/components/Upload/singleUpload"
	import EmojiElement from "@/components/EmojiElement/EmojiElement"
	import LengMessage from "@/components/LengMessage/LengMessage"

	export default {
		name: "pageMsg",
		props: {

		},
		components: {
			singleUpload,
			EmojiElement,
			LengMessage
		},

		data() {
			let pageSizes = 50
			return {
				onlineUsersLength: 1, //在线人数
				contentMaxlength: 15000, //聊天字数限制,
				isShowName: true, //是否显示聊天姓名
				//用户 接受方信息 
				activeItem: {
					type: 1, //信息业务1：文字  11：图片
					fromId: 0, //发送方id
					fromName: "", //发送方名称
					fromUrl: "", //发送方头像
					oldIndex: 0, //上一个
					activeId: 1, //激活id / 接收方id
					isGroup: 1, //是否是群组
					otherName: "社会数官方", //接收方名称
					message: "",
					imagesUrl: "", //图片地址
					isneed: 0, //是否是必须进的群
					msglength: 0, ////信息字数
				},
				allMessageList: {}, //显示的信息列表
				messageList: [],
				pageConfig: {
					pageSizes: pageSizes, //信息条数
					pageNum: 1, //页数 第n页
				},
				isShowNewmobileMsgTip: false, //本页 新消息 提示
				isShowNewmobileTip: false, //下滑操作
				difference: 0, // 计算滚动条差值
				dialogVisibleMobileSendImage: false, //发送图片的dialog标识
				VisibleEmojiElement: false, //表情包的dialog标识
				previewList: [], //聊天预览图列表
				originalPreviewList: [], //聊天预览图列表 原始数据
			}
		},
		mounted() {
			//获取用户信息
			// this.handleResize();
			// window.addEventListener('resize', this.handleResize);

		},
		computed: {
			storeUserinfo() {
				return this.$store.getters.userInfo;
			},
			newMessage() {
				return this.$store.getters.newMessage
			},
			//信息页面预览图列表
			messagePreviewList() {
				return this.previewList
			},
			isExecute() {
				return this.$store.getters.isExecute
			}
		},
		beforeDestroy() {
			// 在组件销毁前移除事件监听
			document.removeEventListener('click', this.handledVisibleEmojiElement);
			// window.removeEventListener('resize', this.handleResize)
		},
		methods: {

			// handleResize() {
			// 	if (window.matchMedia('(max-width:768px)').matches) {
			// 		this.initInfomation();
			// 	}
			// },
			//第一层图片错误触发
			handledImagesErrorOne(url, index) {
				let newURL = this.$handledImageError(url, 'msg')
				this.messageList[index].imagesUrl = newURL;
				let plindex = this.previewList.indexOf(url)
				if (plindex != -1) {
					this.previewList[plindex] = newURL
				}
			},
			//emoji事件显隐处理 检查事件的目标是否在当前组件的DOM元素内
			handledVisibleEmojiElement(data) {
				if (!this.$refs["RefEmojiElement"].contains(event.target)) {
					this.VisibleEmojiElement = false;
				}
			},
			//emoji事件显隐处理
			handledVisibleEmojiElementChildEmit(obj) {
				this.VisibleEmojiElement = obj.VisibleEmojiElement;
				this.activeItem.message = this.activeItem.message + obj.value;
			},
			//发送信息image
			handleSendImage: debounce(function() {
				this.activeItem.type = 11;
				if (this.activeItem.imagesUrl.trim().length === 0) {
					this.$notify({
						title: '',
						message: 'Error:need select image',
						type: 'info',
						duration: 800
					})
					return;
				}
				try {
					this.$store.commit("setOnSend", this.activeItem)
					this.dialogVisibleMobileSendImage = false;
				} catch (e) {
					this.$notify({
						title: '',
						message: 'Error:send images \n请检查网络设置',
						type: 'error',
						duration: 3000
					})
				}


			}),
			//发送信息image 关闭回调
			handleCloseSendImage() {
				this.activeItem.imagesUrl = ""
				this.activeItem.type = 1;
			},
			initInfomation() {
				let userInfo = this.storeUserinfo.Id ? this.storeUserinfo : JSON.parse(Storage.getSession())
				this.activeItem.fromId = userInfo.Id;
				this.activeItem.fromName = userInfo.username;
				this.activeItem.fromUrl = userInfo.url;
				//获取信息列表 获取公共群聊的信息
				this.handleGetMessageList(this.activeItem.activeId)
			},
			/**
			 * 获取指定聊天信息列表
			 */
			handleGetMessageList(otherId) {
				this.previewList = []
				this.originalPreviewList = []
				if (!this.activeItem.fromId) {
					return
				}
				let obj = {
					fromId: this.activeItem.fromId,
					otherId: otherId,
					isGroup: this.activeItem.isGroup,
					pageSizes: this.pageConfig.pageSizes,
					pageNum: this.pageConfig.pageNum
				}
				IMGetMessage(obj).then(data => {
					if (data.count) {
						//时间处理
						this.messageList = this.handlerDate(data.data);
						this.handlerScrollDown("MobilScrollBoxRef");
					}
				})
			},
			//设置信息列表
			handledChangeMessageList(data) {
				this.$set(this.messageList, this.messageList.length, data);
				if (data.type === 11) {
					this.previewList.push(data.imagesUrl)
					this.originalPreviewList.push(data.imagesUrl)
				}
			},
			//发送信息
			handleSend: debounce(function() {
				let l = this.activeItem.message.trim().length;
				this.activeItem.type = 1;
				if (l === 0) {
					this.$notify({
						title: '',
						message: '不能发送空白消息',
						type: 'info',
						duration: 800
					})
					return;
				}
				this.activeItem.msglength = l;
				this.$store.commit("setOnSend", this.activeItem)
			}),
			// 处理内容框的消息提示按钮
			handlerShowTip() {
				this.isShowNewmobileMsgTip = false;
				this.isShowNewmobileTip = false;
				this.handlerScrollDown("MobilScrollBoxRef");
			},
			// 时间处理
			handlerDate(arr) {
				let plist = []
				for (let i = 0; i < arr.length; i++) {
					arr[i].createTime = getdate(arr[i].createTime)
					if (arr[i].type == 11) {
						plist.push(arr[i].imagesUrl)
					}
				}
				this.previewList = this.originalPreviewList = plist;
				return arr;
			},
			//判断日期是否相同 index 截取的字数
			formatDate(endd, index = 100) {
				if (!endd) {
					return "";
				}
				return DateIfSimilar(Date(), endd) ? formatDateHMS(endd).substring(0, index) : endd
					.substring(0,
						index);
			},
			//滚到底部
			handlerScrollDown(refName) {
				this.$nextTick(() => {
					try {
						this.$refs[refName].scrollTop = this.$refs[refName].scrollHeight;
					} catch (e) {
						//TODO handle the exception
					}
				})
			},
			//监听滚动条是否在底部 有信息的情况下 滚动条在底部 就把提示隐藏
			handleWatchScroll(value) {
				let _this = this;
				clearTimeout(_this.item);
				let num = this.$refs["MobilScrollBoxRef"].scrollHeight - this.$refs["MobilScrollBoxRef"].scrollTop - this
					.$refs["MobilScrollBoxRef"].clientHeight;
				if (num < 75) {
					this.isShowNewmobileMsgTip = false;
					this.isShowNewmobileTip = false;
					return;
				}

				_this.item = setTimeout(() => {
					let newDifference = this.$refs["MobilScrollBoxRef"].scrollHeight - this.$refs[
							"MobilScrollBoxRef"]
						.scrollTop;
					if (_this.difference - newDifference > 75) {
						_this.isShowNewmobileTip = true;
						clearTimeout(_this.item)
					} else {
						_this.isShowNewmobileTip = false;
					}
					_this.difference = newDifference
				}, 700)

			},
			//按键 快捷键
			handleEnterKey(value) {
				let l1 = this.activeItem.message.length;
				let l2 = this.activeItem.message.trim().length
				if (l1 != 0 && l2 === 0) {
					this.activeItem.message = ""
				}
				if (l2 === 0) {
					return
				}
				if (!value.ctrlKey) {
					this.handleSend();
				} else {
					this.activeItem.message += '\n'
				}

			},
			//消息文本操作
			beforeHandleCommand(type, value) {
				return {
					type,
					value
				}
			},
			handleCommand(key) {
				if (key.type === 'copy') {
					let value = key.value.type === 1 ? key.value.message : key.value.imagesUrl
					this.$handledMsgCopy(value)
				}
			},

		},

		watch: {

			"storeUserinfo": {
				deep: true,
				immediate: true,
				handler: function(value, oldvalue) {
					this.activeItem.fromId = value.Id;
					this.activeItem.fromName = value.username;
					this.activeItem.fromUrl = value.url;
					//获取信息列表 获取公共群聊的信息
					this.handleGetMessageList(this.activeItem.activeId)
				}
			},
			"VisibleEmojiElement": {
				deep: true,
				immediate: false,
				handler: function(value, oldvalue) {
					if (value) {
						//监听
						document.addEventListener('click', this.handledVisibleEmojiElement);
					} else {
						//移除
						document.removeEventListener('click', this.handledVisibleEmojiElement);
					}
				}
			},
			"newMessage": {
				deep: true, // 深度监听
				handler: function(newVal, oldVal) { // 监听属性的回调方法
					//判断消息类型
					if (this.$store.getters.isExecute) return
					let type = newVal.type;
					if (type === 1 && !this.isExecute) {

						let myId = this.activeItem.fromId; //我是谁 用户ID
						let myActiveId = this.activeItem.activeId; //我的发送目标ID是谁
						let myActiveIsGroup = this.activeItem.isGroup; //我的发送目标是否是群聊
						let fromId = newVal.data.fromId; //发送方 用户ID
						let toActiveId = newVal.data.activeId; //发送方的发送目标 群ID或用户ID
						let isGroup = newVal.data.isGroup; //发送方的发送目标 是否是群聊
						/*新消息 */
						let num = this.$refs["MobilScrollBoxRef"].scrollHeight - this.$refs["MobilScrollBoxRef"]
							.scrollTop - this.$refs["MobilScrollBoxRef"].clientHeight;
						let isTrue = false; //true 滚到底部
						if (myId == fromId && myActiveId == toActiveId && myActiveIsGroup == isGroup) {
							//自己多端发送在同一个页面 包括自己
							isTrue = num < 75;
							num >= 75 ? this.isShowNewmobileMsgTip = true : ""
							this.handledChangeMessageList(newVal.data)
							// 设置数据同步
							// this.handleTimeMsgUp(toActiveId, newVal.data.message, isGroup);
						} else if (myId == fromId) {
							// this.handleTimeMsgUp(toActiveId, newVal.data.message, isGroup);
						} else if (myId == toActiveId && isGroup == 0) {
							//别人 私发
							//在该页面
							if (myActiveId !== fromId) {
								this.$notify({
									title: '新消息',
									message: newMsg,
									type: 'success',
									duration: 2750
								});
								// this.handleTimeMsgUp(fromId, newVal.data.message, isGroup, true);
							} else {
								isTrue = num < 75;
								num >= 75 ? this.isShowNewmobileMsgTip = true : ""
								this.handledChangeMessageList(newVal.data)
								// 设置数据同步
								// this.handleTimeMsgUp(fromId, newVal.data.message, isGroup);
							}
						} else if (myActiveIsGroup == 1 && isGroup == 1) {
							//别人群发
							//在该页面
							if (myActiveId == toActiveId) {
								isTrue = num < 75;
								num >= 75 ? this.isShowNewmobileMsgTip = true : ""
								this.handledChangeMessageList(newVal.data)
								// 设置数据同步
								// this.handleTimeMsgUp(toActiveId, newVal.data.message, isGroup);
							} else {
								//不在该页面
								this.$notify({
									title: '新消息',
									message: newMsg,
									type: 'success',
									duration: 750
								});
								// this.handleTimeMsgUp(toActiveId, newVal.data.message, isGroup, true);
							}

						}

						if (isTrue) {
							this.handlerScrollDown("MobilScrollBoxRef");
						}

					} else if (type === 7 && !this.isExecute) {
						//信息发送状态
						if (newVal.status) {
							this.activeItem.message = "";
							this.handlerScrollDown("MobilScrollBoxRef");
						}
					} else if (type === 3) {
						let arr = []
						if (typeof newVal.data == 'object') {
							for (let key in newVal.data) {
								arr.push(newVal.data[key])
							}
						}
						// console.log("非聊天消息类型的---上下线提示")
						this.onlineUsersLength = arr.length
					}
				},
				immediate: false // 页面初始化时是否触发回调
			},


		}

	}
</script>
<style scoped>
	.contentTop {
		line-height: 25px;
		background-color: #aaffff;
		border-radius: 10px;
	}

	.mobileContentMiddle {
		width: 100%;
		/* height: calc(100vh - 226px); */
		height: auto;
		overflow-y: auto;
		border-top: 1px solid #ccc;
		border-bottom: 1px solid #ccc;
		position: fixed;
		bottom: 183px;
		top: 38px;
	}

	/* 标题 */
	.mobileContentTitle {
		width: 85vw;
		margin: 8px 12px;
		font-size: 16px;
	}



	/* 消息提示 */
	.mobilemobileMsgTipBox {
		position: fixed;
		bottom: 205px;
		right: 0;
	}

	.mobileMsgTip {
		cursor: pointer;
		text-align: center;
		height: 35px;
		line-height: 35px;
		padding: 0 12px 0 12px;
		border-radius: 12px 0 0 12px;
		background-color: #aaffff;
	}

	.mobileMsgTip:hover {
		background-color: #a2f3f3;
	}

	.mobileMsgTip:active {
		background-color: #94dede;
	}

	.mobileMsgTip span {
		margin-left: 3px;
		font-size: 14px;
	}

	.icon-shuangxiangxiajiantou:before {
		animation-name: example;
		animation-duration: .6s;
		animation-iteration-count: infinite;
		animation-direction: alternate-reverse;
		color: #e6e6e6;
	}

	/* 动画代码 */
	@keyframes example {
		0% {
			color: #e6e6e6;
		}

		100% {
			color: #00aaff;
		}
	}


	.fromMessageMobilPadding {
		padding: 3px 12px;
		max-width: 72vw;
		box-sizing: border-box;
	}


	.msgBottomBox {
		position: fixed;
		bottom: 56px;
		width: 100%;
		height: 130px;
		box-sizing: border-box;
	}

	.msgBottomBox .contentDown {
		max-height: 100px;
	}

	.hintContentButtom {
		width: 100%;
		height: 30px;
		line-height: 30px;
		display: flex;
		box-sizing: border-box;
		justify-content: space-between;
		align-items: center;
		padding: 0 25px;
	}

	.hintContentButtom .buttomLeft {
		display: flex;
		justify-content: center;
		align-content: center;
	}

	.hintContentButtom .buttomLeft .emojiButton {
		position: relative;
		margin-left: 8px;
	}

	/*字数提示*/
	.hintContentLength {
		display: inline-block;
		right: 80px;
		height: 30px;
		line-height: 30px;
		color: #ccc;
		font-size: 12px;
		margin-right: 10px;
	}

	.hintContentNowLength {
		display: inline-block;
		font-size: 14px;
	}
</style>